var express = require('express');
var jwt = require('jwt-simple');
var app = express();
app.set('jwtTokenSecret', 'CloudBooking');

var moment = require('moment');


/*
type:md5,md4,sha1
*/
exports.encrypt = function (pwd,type) {
	var crypto = require('crypto');  
	var r = crypto.createHash(type);//定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    r.update(pwd);
    return r.digest('hex');    
};



//Token 创建
exports.jwtCreateToken = function (code) {
	var expires = moment().add(7, 'days').format('YYYY-MM-DD HH:mm:ss');
	var token = jwt.encode({
	  code: code,
	  exp: expires
	}, app.get('jwtTokenSecret'));
	return token;
};


//验证token是否失效(true:token有效，false：token过期)
exports.getTokenObj = function (req) {
	var tokenObj={status:false};
	try{
		var token=req.cookies['token'];
	    if(token!=null||token!=""||token!=undefined){
			var decoded = jwt.decode(token, app.get('jwtTokenSecret'));
			tokenObj.status=!moment().isAfter(decoded.exp);
			tokenObj.tokenData=decoded;
		}
	}
	catch(ex){}	
	return tokenObj;
}

